<template>
  <div>
    <div v-if="!userGroups">
      <Error></Error>
    </div>
    <div v-if="userGroups">
      <div class="userGroup" v-loading="loading">
        <el-row>
          <el-table
            :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
            style="width: 100%">
            <el-table-column
              prop="number"
              label="序号"
              width="48">
            </el-table-column>
            <el-table-column
              prop="name"
              label="名称"
              width="80">
            </el-table-column>
            <el-table-column
              width="60"
              label="状态">
              <template slot-scope="scope">
                <span style="color:#F56C6C" v-if="scope.row.status == '2'">禁用</span>
                <span style="color:#409EFF" v-if="scope.row.status == '1'">正常</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="create_time"
              label="创建时间"
              sortable
              width="200">
            </el-table-column>
            <el-table-column
              align="right">
              <template slot="header" slot-scope="scope">
                <div class="el-table-header">
                  <el-input v-model="search"
                            placeholder="输入姓名关键字搜索"/>
                  <el-button type="primary" @click.native.prevent="addInformation" :class="edUser" v-if="addUserGroup">添加</el-button>
                </div>
              </template>
              <template slot-scope="scope">
                <el-button
                  @click.native.prevent="compileRow(scope.$index,tableData)"
                  size="small"
                  v-if="editGroupPermission"
                >
                  编辑权限
                </el-button>
                <el-button
                  @click.native.prevent="revisionRow(scope.$index,scope.row)"
                  type="primary"
                  size="small"
                  v-if="editUserGroup"
                >
                  修改
                </el-button>
                <!--<el-button-->
                <!--@click.native.prevent="deleteRow(scope.$index,tableData)"-->
                <!--type="danger"-->
                <!--v-if="delUserGroup"-->
                <!--size="small">-->
                <!--删除-->
                <!--</el-button>-->
                <el-button v-show="scope.row.status == '1'"
                           @click.native.prevent="deleteRow(scope.$index,tableData,2)"
                           type="danger"
                           v-if="editGroupStatus"
                           size="small">
                  禁用
                </el-button>
                <el-button v-show="scope.row.status !== '1'"
                           @click.native.prevent="deleteRow(scope.$index,tableData,1)"
                           type="success"
                           v-if="editGroupStatus"
                           size="small">
                  启用
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!--添加数据-->
          <el-dialog title="添加用户分组" :visible.sync="dialogFormVisibleData">
            <el-form :rules="rules"  ref="formData" :model="formData" :label-position="labelPosition" style="width: 50%;margin-left: 25%">
              <el-form-item label="分组名称" :label-width="formLabelWidth" prop="name">
                <el-input v-model="formData.name" autocomplete="off" placeholder="请输入分组名称"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click.native.prevent="dialogFormVisibleData = false">取 消</el-button>
              <el-button type="primary" @click.native.prevent="dataSuccess('formData')">确 定</el-button>
            </div>
          </el-dialog>

          <!--修改-->
          <el-dialog title="修改用户分组" :visible.sync="dialogFormVisible">
            <el-form :rules="rules" ref="alterFormData" :model="alterFormData" :label-position="labelPosition" style="width: 50%;margin-left: 25%">
              <el-form-item label="分组名称" :label-width="formLabelWidth" prop="name">
                <el-input v-model="alterFormData.name" autocomplete="off" placeholder="请输入分组名称"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click.native.prevent="dialogFormVisible = false">取 消</el-button>
              <el-button type="primary" @click.native.prevent="alterDataSuccess('alterFormData')">确 定</el-button>
            </div>
          </el-dialog>

          <el-col :span="24">
            <div class="block" v-if="total">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-size="10"
                layout="total, prev, pager, next"
                :total="total">
              </el-pagination>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
  import Error from '../errorPage/errorPage401'
  export default {
    data() {
      return {
        mid:'',
        loading:false,
        confirmIndex:'',

        editGroupPermission:false,
        editUserGroup:false,
        editGroupStatus:false,
        addUserGroup:false,
        userGroups:false,
        edUser:'',
        obj:{},
        search:"",
        total:"",
        currentPage:"",
        dialogFormVisibleData:false,
        dialogFormVisible:false,
        formLabelWidth:'80px',
        labelPosition:"left",
        tableData: [],
        formData:{
          name:"",
        },
        alterFormData:{
          name:"",
        },
        rules:{
          name:[
            { required: true, message: '分组名不能为空', trigger: 'blur' },
          ],
        },
      }
    },
    methods: {
      userGroup:function(page){
        //获取分组信息
        let data = {
          page: page
        };
        let str = this.encryptionAesRsa(data);
        let encryptData = str.split('%$#@zjt@#$%')[0];
        let encryptKey = str.split('%$#@zjt@#$%')[1];
        let incomData = {
          map: 'admin_group_list',
          plum_session_api: localStorage.getItem('token'),
          encryptData: encryptKey,
          encryptKey: encryptData
        };
        this.$http.post('', incomData).then((data) => {
          if (data.ec == 200) {
            this.loading = false;
            this.tableData = data.data.list;
            this.total = Number(data.data.total);
            this.currentPage = Number(data.data.current_page);
          } else if (data.ec == 401) {
            this.$message.error(data.em);
            setTimeout(() => {
              this.exitLogin();
            }, 1500)
          } else {
            this.$message.error(data.em);
          }
        }).catch((err) => {
          this.$message.error('error!');
        })
      },
      addInformation:function () {
        this.dialogFormVisibleData = true;
      },
      handleSizeChange(val) {

      },
      handleCurrentChange(val) {
        this.$router.replace({
          path: this.$route.path,
          query: {
            page: val,
          }
        });
        this.loading = true;
        this.userGroup(val);
      },
      //添加用户分组
      dataSuccess:function (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let data = {
              name:this.formData.name
            };
            let str = this.encryptionAesRsa(data);
            let encryptData = str.split('%$#@zjt@#$%')[0];
            let encryptKey = str.split('%$#@zjt@#$%')[1];
            let incomData = {
              map: 'admin_group_edit',
              plum_session_api: localStorage.getItem('token'),
              encryptData: encryptKey,
              encryptKey: encryptData
            };
            this.$http.post('', incomData).then((data) => {
              if (data.ec == 200) {
                this.$message.success(data.em);
                this.formData.name="";
                this.dialogFormVisibleData = false;
                this.userGroup(this.currentPage);
              } else if (data.ec == 401) {
                this.$message.error(data.em);
                setTimeout(() => {
                  this.exitLogin();
                }, 1500)
              } else {
                this.$message.error(data.em);
              }
            }).catch((err) => {
              this.$message.error('error!');
            })
          } else {
            return false;
          }
        });
      },
      //  修改
      revisionRow:function (index,row) {
        this.mid = row.id;
        this.dialogFormVisible = true;
        this.alterFormData.name = row.name;
      },
      //确定修改数据
      alterDataSuccess:function(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let data = {
              group_id:this.mid,
              name:this.alterFormData.name
            };
            let str = this.encryptionAesRsa(data);
            let encryptData = str.split('%$#@zjt@#$%')[0];
            let encryptKey = str.split('%$#@zjt@#$%')[1];
            let incomData = {
              map: 'admin_group_edit',
              plum_session_api: localStorage.getItem('token'),
              encryptData: encryptKey,
              encryptKey: encryptData
            };
            this.$http.post('', incomData).then((data) => {
              if (data.ec == 200) {
                this.$message.success(data.em);
                this.alterFormData.name="";
                this.dialogFormVisible = false;
                this.userGroup(this.currentPage);
              } else if (data.ec == 401) {
                this.$message.error(data.em);
                setTimeout(() => {
                  this.exitLogin();
                }, 1500)
              } else {
                this.$message.error(data.em);
              }
            }).catch((err) => {
              this.$message.error('error!');
            })
          } else {
            return false;
          }
        });
      },
      //修改用户状态
      deleteRow(index, row,status) {
        this.mid = row[index].id;
        let str = '';
        if(status == 1){
          str='此操作将启用该用户, 是否继续?'
        }else {
          str='此操作将禁用该用户, 是否继续?'
        }
        this.$confirm(str, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data = {
            group_id:this.mid,
            status:status
          };
          let str = this.encryptionAesRsa(data);
          let encryptData = str.split('%$#@zjt@#$%')[0];
          let encryptKey = str.split('%$#@zjt@#$%')[1];
          let incomData = {
            map:'admin_group_status_edit',
            plum_session_api:localStorage.getItem('token'),
            encryptData:encryptKey,
            encryptKey:encryptData
          };
          this.$http.post('',incomData).then((data)=>{
            if(data.ec==200){
              this.$message.success(data.em);
              this.userGroup(this.currentPage)
            }else if(data.ec==401){
              this.$message.error(data.em);
              setTimeout(()=>{
                this.exitLogin();
              },1500)
            }else {
              this.$message.error(data.em);
            }
          }).catch((err)=>{
            this.$message.error('error!');
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      },
      //编辑小组权限
      compileRow:function (index,rows) {
        sessionStorage.setItem('jurisdictionId',rows[index].id);
        this.$router.push('/editPermission')
      }
    },
    created() {
      //获取分组信息
      this.currentPage = this.$route.query.page ? this.$route.query.page : 1;
      this.userGroup(this.currentPage);
      this.loading = true;
      //获取按钮权限
    },
    mounted() {
      // 按钮权限
      let buttonMenu = localStorage.getItem('buttonMenu');
      buttonMenu = this.edecryptButton(buttonMenu);
      if(buttonMenu.indexOf('editGroupPermission')!==-1){
        this.editGroupPermission = true
      }
      if(buttonMenu.indexOf('editUserGroup')!==-1){
        this.editUserGroup = true
      }
      if(buttonMenu.indexOf('editGroupStatus')!==-1){
        this.editGroupStatus = true
      }
      if(buttonMenu.indexOf('addUserGroup')!==-1){
        this.addUserGroup = true
      }
    //  页面权限
      if (buttonMenu.indexOf('userGroup') !== -1) {
        this.userGroups = true
      }
    },
    components:{
      Error
    }
  }
</script>

<style scoped>
  .el-col {
    border-radius: 4px;
    height: 75px;
    background-color: #fff;
  }
  .el-table-header>>>.el-input{
    width: 200px;
    float: left;
    height: 40px;
  }
  .el-table-header>>>.el-button{
    float: right;
    height: 40px;
  }
  .block>>>.el-pagination{
    height: 30px;
    line-height: 30px;
    margin-top: 25px;
    text-align: center;
  }
</style>
